package com.open.companymessage.company.service.impl;

import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.model.*;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.companymessage.company.dao.CUserRoleDao;
import com.open.companymessage.company.dao.CompanyDao;
import com.open.companymessage.company.feign.FeignService;
import com.open.companymessage.company.service.CompanyService;

import com.open.companymessage.company.service.RoleService;
import com.open.companymessage.company.vo.UserCompany;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

@Slf4j
@Service
public class CompanyServiceImpl implements CompanyService {
    @Resource
    private CompanyDao companyDao;
    @Autowired
    private FeignService feignService;
    @Autowired
    private CUserRoleDao cUserRoleDao;


    /**
     * 先注册公司，然后返回id，将id保存到sys_user中的company_id,然后注册user
     * @param userCompany
     * @return
     */
    @Override
    @Transactional
    public Result addCompany(UserCompany userCompany,String token) {
        boolean isHave = isHaveComName(userCompany.getCompanyName());
        if (isHave) {
            int i = companyDao.addCompany(userCompany);
            if (StringUtils.isBlank(userCompany.getUsername())
                    || StringUtils.isBlank(userCompany.getPassword())) {
                return Result.succeed(i, "公司注册成功");
            }
            if (i > 0) {
                SysUser user = new SysUser();
                user.setUsername(userCompany.getUsername());
                user.setPassword(userCompany.getPassword());
                user.setCompanyId(userCompany.getId());
                Result result = feignService.addSysUser(user);
                if (result.getData() !=null) {
                    /**
                     * 给用户设置角色
                     */
                    try {
                        HashMap<String, Object> params = new HashMap<>();
                        params.put("access_token",token);
                        PageResult<SysRole> roles = feignService.findRoles(params);
                        List<SysRole> data = roles.getData();
                        Long roleId = null;
                        for (int j = 0; j< data.size(); j++) {
                            if ("COMPANY".equals(data.get(j).getCode()))
                                roleId=data.get(j).getId();
                        }
                        HashMap map = (HashMap) result.getData();
                        user.setId(Long.parseLong(map.get("id").toString()));
                        feignService.setRoleToUserFree(user.getId(), roleId);
                    } catch (Exception e) {
                        throw new ServiceException(e);
                    }
                }
                return Result.succeed(result.getData(), "添加成功");
            }
            return Result.failed("添加失败了....");
        } else {
            return Result.failed("公司名称已存在，请勿重复添加");
        }
    }



    //判断公司名称是否已经存在
    private boolean isHaveComName(String companyName) {
        List<SysCompany> list = new ArrayList<>();
        list = companyDao.isHaveComName(companyName);
        return list.size() == 0;
    }



    @Override
    public Result updateCompany(SysCompany sysCompany) {
        return Result.succeed(companyDao.updateCompany(sysCompany),"修改成功");
    }

    @Override
    public List<SysCompany> selectCompany(Map<String,Object> map) {
        Object userId1 = map.get("userId");
        long userId = 0;
        boolean isAdmin=false; //默认不是管理员
        if(userId1!=null){
            userId = Long.valueOf(map.get("userId").toString());
            Set<SysRole> rolesByUserId = cUserRoleDao.findRolesByUserId(userId);
            Iterator<SysRole> iterator = rolesByUserId.iterator();
            while (iterator.hasNext()){
                SysRole next = iterator.next();
                if(next.getCode().equals("ADMIN")){
                    isAdmin=true;
                    break;
                }
            }
        }

        if(isAdmin) {
            map.remove("userId");
        }else {
            SysUser user = cUserRoleDao.findUserById(userId);
            Long companyId = user.getCompanyId();
            map.remove("userId");
            map.put("companyId",companyId);
        }

        List<SysCompany> list = companyDao.selectCompany(map);
        return list;
    }

    @Override
    public Result deleteCompany(Long id) {
        return Result.succeed(companyDao.deleteCompany(id),"删除成功");
    }

    /**
     * 查询公司和活动关联的相关数据
     * @param map
     * @return
     */
    @Override
    public List<CompanyActive> selectCompanyActive(Map<String, Object> map) {
        List<CompanyActive> list = companyDao.selectCompanyActive(map);
        return list;
    }

    /**
     * 添加公司和活动相关的数据id
     * @param companyActive
     * @return
     */
    @Override
    public Result insertCompanyID(CompanyActive companyActive) {
        return Result.succeed(companyDao.insertCompanyID(companyActive),"添加成功");
    }

    /**
     * 根据id删除公司和活动相关的数据
     * @param companyActive
     * @return
     */
    @Override
    public Result deleteCompanyActiveId(CompanyActive companyActive) {
        return Result.succeed(companyDao.deleteCompanyActiveId(companyActive),"删除成功");
    }

}
